<script lang="ts" setup>
import dayjs, { OpUnitType } from 'dayjs'
import { Action, DateModelType, ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, defineAsyncComponent } from 'vue'
import {
  acceptWorkOrder,
  cancelWorkOrder,
  finishWorkOrder,
  queryWorkOrder,
  queryWorkOrderLog,
  remarkWorkOrder
} from '@/api/operation'
import { queryWorkOrderTableCol } from '@/api/operation/types/operation'
import { getToken } from '@/utils/cache/cookies'
import { useTable } from '@/hooks/useTable'
import { FormInstance } from 'ant-design-vue'
import { formatterWorkOrderStatus } from '@/utils/formatter'
import { workOrderUrgencyType } from '@/types/enum'
defineOptions({
  name: 'WorkOrder'
})
const form = reactive({
  workOrderId: '',
  deviceCode: '',
  dispatcher: '',
  deviceType: '',
  type: '',
  urgency: '',
  status: '',
  scheduleStartTime: '',
  scheduleEndTime: '',
  receiveStartTime: '',
  receiveEndTime: '',
  receiver: '1'
})
const formRef = ref<FormInstance | null>(null)
type ModelDateType = string | number | Date | [DateModelType, DateModelType]
const scheduleTime = ref<ModelDateType>('')
const handleScheduleDateChange = (value: string[] | string) => {
  if (value && value.length === 2) {
    form.scheduleStartTime = value[0]
    form.scheduleEndTime = value[1]
  } else {
    form.scheduleStartTime = dayjs(value as string)
      .startOf(scheduleTime.value as OpUnitType)
      .format('YYYY-MM-DD HH:mm:ss')
    form.scheduleEndTime = dayjs(value as string)
      .endOf(scheduleTime.value as OpUnitType)
      .format('YYYY-MM-DD HH:mm:ss')
  }
}
const { data, loading, pagination, load, handleCurrentChange, handleSizeChange, setCurrentPage } =
  useTable<queryWorkOrderTableCol>(queryWorkOrder, getToken() ?? '', () => form)

const handleFormSearch = () => {
  setCurrentPage(1)

  load()
}
const reset = () => {
  formRef.value?.resetFields()
}

const workOrderUrgencyColor = (urgency: workOrderUrgencyType) => {
  switch (urgency) {
    case '普通':
      return {
        color: 'var(--xy-color-blue)'
      }
    case '紧急':
      return {
        color: 'var(--xy-primary-color)'
      }
    case '重要':
      return {
        color: 'var(--xy-warning-color)'
      }
    case '较低':
      return {
        color: 'var(--xy-success-color)'
      }
    default:
      break
  }
}

onMounted(() => {
  load()
})

const AddWorkOrderDialog = defineAsyncComponent(
  () => import('@/components/dialog/AddWorkOrder.vue')
)
const AddWorkOrderDialogRef = ref<InstanceType<typeof AddWorkOrderDialog> | null>(null)

const RemarkDialog = defineAsyncComponent(
  () => import('@/components/basic/BasicTextAreaDialog.vue')
)
const RemarkDialogRef = ref<InstanceType<typeof RemarkDialog> | null>(null)

const DispatchWorkOrderDialog = defineAsyncComponent(
  () => import('@/components/dialog/DispatchWorkOrder.vue')
)
const DispatchWorkOrderDialogRef = ref<InstanceType<typeof DispatchWorkOrderDialog> | null>(null)

const WorkOrderLogDialog = defineAsyncComponent(
  () => import('@/components/basic/BasicStepDialog.vue')
)
const WorkOrderLogDialogRef = ref<InstanceType<typeof WorkOrderLogDialog> | null>(null)
const WorkRemarkLogDialogRef = ref<InstanceType<typeof WorkOrderLogDialog> | null>(null)
const addOrder = () => {
  AddWorkOrderDialogRef.value?.open()
}

const dispatch = (row: queryWorkOrderTableCol) => {
  DispatchWorkOrderDialogRef.value?.setData(row.deviceCode, row.receiverName, row.workOrderId)
  DispatchWorkOrderDialogRef.value?.open()
}
const remark = (row: queryWorkOrderTableCol) => {
  RemarkDialogRef.value?.setId(row.workOrderId, '备注')
  RemarkDialogRef.value?.open()
}
const cancelOrder = async (row: queryWorkOrderTableCol) => {
  try {
    ElMessageBox.alert('取消工单后，需要重新添加工单，是否需要取消工单', '取消工单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      showCancelButton: true,
      callback: async (action: Action) => {
        if (action === 'confirm') {
          const res = await cancelWorkOrder({
            workOrderId: row.workOrderId,
            token: getToken() ?? ''
          })
          if (res.statusCode === '0') {
            ElMessage.success(res.data)
            load()
          }
        }
      }
    })
  } catch (error) {
    console.error(error)
  }
}
const acceptOrder = (row: queryWorkOrderTableCol) => {
  try {
    ElMessageBox.alert('接取工单后，工单开始计时，是否接取工单', '接取工单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      showCancelButton: true,
      callback: async (action: Action) => {
        if (action === 'confirm') {
          const res = await acceptWorkOrder({
            workOrderId: row.workOrderId,
            token: getToken() ?? ''
          })
          if (res.statusCode === '0') {
            ElMessage.success(res.data)
            load()
          }
        }
      }
    })
  } catch (error) {
    console.error(error)
  }
}
const finishOrder = async (row: queryWorkOrderTableCol) => {
  try {
    ElMessageBox.alert('请确认该工单是否完成，点击完成后无法恢复', '完成工单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      showCancelButton: true,
      callback: async (action: Action) => {
        if (action === 'confirm') {
          const res = await finishWorkOrder({
            workOrderId: row.workOrderId,
            token: getToken() ?? ''
          })
          if (res.statusCode === '0') {
            ElMessage.success(res.data)
            load()
          }
        }
      }
    })
  } catch (error) {
    console.error(error)
  }
}

const getStepData = async (workOrderId: string, title: string) => {
  try {
    const res = await queryWorkOrderLog({
      token: getToken() ?? '',
      workOrderId: workOrderId,
      type: title === '工单备注' ? 'Remark' : 'Follow'
    })
    if (res.statusCode === '0') {
      return res.data
    } else {
      return []
    }
  } catch (error) {
    console.error(error)
    return []
  }
}

const openRemark = (row: queryWorkOrderTableCol) => {
  WorkRemarkLogDialogRef.value?.setData(row.workOrderId, '工单备注', getStepData)
  WorkRemarkLogDialogRef.value?.open()
}
const submitRemark = async (workOrderId: string, remark: string) => {
  try {
    const res = await remarkWorkOrder({
      token: getToken() ?? '',
      workOrderId: workOrderId,
      remark: remark
    })
    if (res.statusCode === '0') {
      ElMessage.success(res.data)
      RemarkDialogRef.value?.close()
    } else {
      ElMessage.error(res.data)
    }
  } catch (error) {
    console.error(error)
  }
}
const openRecord = (row: queryWorkOrderTableCol) => {
  WorkOrderLogDialogRef.value?.setData(row.workOrderId, '工单跟进记录', getStepData)
  WorkOrderLogDialogRef.value?.open()
}
</script>

<template>
  <div class="xy-container--split">
    <div class="xy-container__header">
      <el-form :model="form" ref="formRef" inline>
        <div flex flex-col>
          <div>
            <el-form-item prop="workOrderId" label="工单编号">
              <el-input v-model="form.workOrderId" placeholder="请输入工单编号" />
            </el-form-item>
            <el-form-item prop="deviceCode" label="设备编号">
              <el-input v-model="form.deviceCode" placeholder="请输入设备编号" />
            </el-form-item>
            <el-form-item prop="deviceType" label="设备类型">
              <el-select v-model="form.deviceType" placeholder="请选择设备类型" w-160>
                <el-option label="不限" value="" />
                <el-option label="长租车" value="长租车" />
                <el-option label="短租车" value="短租车" />
                <el-option label="换电柜" value="换电柜" />
                <el-option label="电池" value="电池" />
                <el-option label="民用车" value="民用车" />
                <el-option label="改装车" value="改装车" />
              </el-select>
            </el-form-item>
            <el-form-item prop="type" label="工单分类">
              <el-select v-model="form.type" placeholder="请选择工单分类" w-160>
                <el-option label="不限" value="" />
                <el-option label="故障" value="故障" />
                <el-option label="换电" value="换电" />
                <el-option label="调度" value="调度" />
                <el-option label="巡检" value="巡检" />
                <el-option label="维修" value="维修" />
                <el-option label="寻找" value="寻找" />
                <el-option label="事故" value="事故" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
            <el-form-item prop="status" label="工单状态">
              <el-select v-model="form.status" placeholder="请选择工单状态" w-160>
                <el-option label="不限" value="" />
                <el-option label="待处理" value="待处理" />
                <el-option label="已接单" value="已接单" />
                <el-option label="待审核" value="待审核" />
                <el-option label="已取消" value="已取消" />
                <el-option label="已完成" value="已完成" />
              </el-select>
            </el-form-item>
          </div>
          <div flex justify-between>
            <div>
              <el-form-item prop="urgency" label="紧急程度">
                <el-select v-model="form.urgency" placeholder="请选择紧急程度" w-150>
                  <el-option label="不限" value="" />
                  <el-option label="紧急" value="紧急" />
                  <el-option label="重要" value="重要" />
                  <el-option label="普通" value="普通" />
                  <el-option label="较低" value="较低" />
                </el-select>
              </el-form-item>
              <el-form-item label="派单时间">
                <el-date-picker
                  v-model="scheduleTime"
                  placeholder="请选择派单时间"
                  type="datetimerange"
                  format="YYYY-MM-DD HH:mm:ss"
                  range-separator="至"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  @change="handleScheduleDateChange"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleFormSearch">查询</el-button>
                <el-button plain @click="reset">重置</el-button>
              </el-form-item>
            </div>
            <el-form-item>
              <el-button type="primary" plain @click="addOrder">添加工单</el-button>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>
    <div class="xy-container__content" mt-20 pb-20>
      <el-table :data="data" v-loading="loading">
        <el-table-column prop="workOrderId" label="工单编号" align="center" min-width="80" />
        <el-table-column
          prop="deviceCode"
          label="设备编号"
          align="center"
          fixed="left"
          min-width="100"
        />
        <el-table-column prop="deviceType" label="设备类型" align="center" min-width="100" />
        <el-table-column
          prop="remark"
          label="工单详情"
          align="center"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column prop="imageUrls" label="工单图片" align="center" min-width="100">
          <template #default="scope">
            <div v-if="scope.row.imageUrls">
              <el-image
                v-for="item in scope.row.imageUrls.split(',')"
                :key="item"
                :src="item"
                :preview-src-list="scope.row.imageUrls.split(',')"
                :preview-teleported="true"
                w-50
                h-50
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="工单分类" align="center" min-width="150" />
        <el-table-column prop="urgency" label="紧急程度" align="center" min-width="100">
          <template #default="scope">
            <span :style="workOrderUrgencyColor(scope.row.urgency)">{{ scope.row.urgency }}</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="status"
          label="工单状态"
          align="center"
          min-width="100"
          :formatter="formatterWorkOrderStatus"
        />
        <el-table-column prop="dispatcher" label="派单人" align="center" min-width="100" />
        <el-table-column
          prop="createdTime"
          label="派单时间"
          align="center"
          min-width="130"
          show-overflow-tooltip
        />
        <el-table-column prop="receiverName" label="接单人" align="center" min-width="140" />
        <el-table-column
          prop="receiveTime"
          label="接单时间"
          align="center"
          min-width="130"
          show-overflow-tooltip
        />
        <el-table-column prop="duration" label="完成时长(h)" align="center" min-width="100" />
        <el-table-column prop="" label="工单备注" align="center" min-width="100">
          <template #default="scope">
            <el-button link class="is-show" @click="openRemark(scope.row)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="" label="工单跟进记录" align="center" min-width="120">
          <template #default="scope">
            <el-button link class="is-show" @click="openRecord(scope.row)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="250" fixed="right">
          <template #default="scope">
            <el-button
              link
              class="is-show"
              @click="acceptOrder(scope.row)"
              v-if="scope.row.status === 'PENDING'"
              >接单</el-button
            >
            <el-button
              link
              class="is-show"
              @click="dispatch(scope.row)"
              v-if="scope.row.status !== 'COMPLETED' && scope.row.status !== 'CANCELLED'"
              >转派</el-button
            >
            <el-button link class="is-show" @click="remark(scope.row)">备注</el-button>
            <el-button
              link
              class="is-show"
              @click="cancelOrder(scope.row)"
              v-if="scope.row.status === 'PENDING' && scope.row.status == 'REVIEWING'"
              >取消</el-button
            >
            <el-button
              link
              class="is-show"
              @click="finishOrder(scope.row)"
              v-if="scope.row.status === 'IN_PROGRESS'"
              >完成</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div flex justify-end mt-20>
        <el-pagination
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          background
          :total="pagination.total"
          layout="total,prev,pager,next,jumper,sizes"
        />
      </div>
    </div>
    <add-work-order-dialog ref="AddWorkOrderDialogRef" @refresh="load" />
    <remark-dialog ref="RemarkDialogRef" @submit="submitRemark" />
    <dispatch-work-order-dialog ref="DispatchWorkOrderDialogRef" @refresh="load" />
    <work-order-log-dialog ref="WorkOrderLogDialogRef" type="image" />
    <work-order-log-dialog ref="WorkRemarkLogDialogRef" type="remark" />
  </div>
</template>

<style scoped></style>
